package cmd

import (
	"regexp"
	"sort"
	"strings"
	"strconv"
)

// 字符串处理相关函数
func convertPunctuation(s string) string {
	replacements := map[string]string{
		"（": "(",
		"）": ")",
		"：": ": ",
		"，": ", ",
		"。": ".",
		"、": ",",
	}
	
	for k, v := range replacements {
		s = strings.ReplaceAll(s, k, v)
	}
	return s
}

// stringWidth 计算字符串显示宽度（中文字符占2个宽度）
func stringWidth(s string) int {
	width := 0
	for _, r := range s {
		if r >= 0x4E00 && r <= 0x9FFF {
			width += 2
		} else {
			width += 1
		}
	}
	return width
}

// padString 填充字符串到指定宽度
func padString(s string, width int) string {
	currentWidth := stringWidth(s)
	if currentWidth >= width {
		return s
	}
	return s + strings.Repeat(" ", width-currentWidth)
}

// 版本号处理相关函数
func normalizeVersion(version string) string {
	if !strings.HasPrefix(strings.ToLower(version), "v") {
		return "v" + version
	}
	return "v" + strings.TrimPrefix(strings.TrimPrefix(version, "V"), "v")
}

// sortVersions 对版本号进行排序
func sortVersions(versions []string) []string {
	versionsWithoutV := make([]string, len(versions))
	for i, v := range versions {
		versionsWithoutV[i] = strings.TrimPrefix(v, "v")
	}

	sort.Slice(versionsWithoutV, func(i, j int) bool {
		return versionsWithoutV[i] < versionsWithoutV[j]
	})

	result := make([]string, len(versionsWithoutV))
	for i, v := range versionsWithoutV {
		result[i] = "v" + v
	}
	return result
}

// cleanDetailPrefix 清理详细信息的前缀
func cleanDetailPrefix(detail string) string {
	// 移除数字+点+空格的前缀（如 "1. "）
	if match := regexp.MustCompile(`^\d+\.\s+`).FindString(detail); match != "" {
		return strings.TrimPrefix(detail, match)
	}
	// 移除无序列表前缀（如 "- " 或 "* "）
	if match := regexp.MustCompile(`^[-*]\s+`).FindString(detail); match != "" {
		return strings.TrimPrefix(detail, match)
	}
	return detail
}

// contains 检查切片中是否包含指定字符串
func contains(slice []string, str string) bool {
	for _, v := range slice {
		if v == str {
			return true
		}
	}
	return false
}

// formatHelp 格式化帮助信息，统一中英文对齐
func formatHelp(cn, en string) string {
	return padString(cn, 20) + "| " + en
}

// convertFormat 将简化的格式模板转换为 Go 模板格式
func convertFormat(format string) string {
	// 转换简化格式到 Go 模板格式
	replacements := map[string]string{
		"{type}": "{{.Type}}",
		"{scope}": "{{.Scope}}",
		"{?scope}": "{{if .Scope}}{{.Scope}}{{end}}",
		"{(scope)}": "{{if .Scope}}({{.Scope}}){{end}}",
		"{[scope]}": "{{if .Scope}}[{{.Scope}}]{{end}}",
		"{title}": "{{.Title}}",
		"{version}": "{{if .Versions}}{{.FirstVersion}}{{if .HasMultipleVersions}}-{{.LastVersion}}{{end}}{{end}}",
		"{?version}": "{{if .Versions}}{{.FirstVersion}}{{if .HasMultipleVersions}}-{{.LastVersion}}{{end}}{{end}}",
		"{(version)}": "{{if .Versions}}({{.FirstVersion}}{{if .HasMultipleVersions}}-{{.LastVersion}}{{end}}){{end}}",
		"{[version]}": "{{if .Versions}}[{{.FirstVersion}}{{if .HasMultipleVersions}}-{{.LastVersion}}{{end}}]{{end}}",
		"{original}": "{{.OriginalTitle}}",
		"{detail}": "{{.Detail}}",
		"{order}": "{{.Order}}",
	}

	// 按照最长匹配优先的原则排序替换
	keys := make([]string, 0, len(replacements))
	for k := range replacements {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool {
		return len(keys[i]) > len(keys[j])
	})

	result := format
	for _, k := range keys {
		result = strings.ReplaceAll(result, k, replacements[k])
	}
	return result
}

// compareVersions 比较两个版本号
func compareVersions(v1, v2 string) bool {
	// 移除 'v' 前缀
	v1 = strings.TrimPrefix(v1, "v")
	v2 = strings.TrimPrefix(v2, "v")
	
	// 将版本号分割为数字部分
	parts1 := strings.Split(v1, ".")
	parts2 := strings.Split(v2, ".")
	
	// 比较每个部分
	for i := 0; i < len(parts1) && i < len(parts2); i++ {
		n1, _ := strconv.Atoi(parts1[i])
		n2, _ := strconv.Atoi(parts2[i])
		if n1 != n2 {
			return n1 < n2
		}
	}
	
	// 如果前面的部分都相等，较短的版本号较小
	return len(parts1) < len(parts2)
} 